﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Configuration;
using System.Configuration;
using System.Xml;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Stone.Library.Common
{
    /// <summary>
    /// 配置文件工具类
    /// </summary>
    public class ConfigHelp
    {
        /// <summary>
        /// 获得键值对的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getAppValue(string key)
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
            {
                return config.AppSettings.Settings[key].Value;
            }
            else
            {
                return null;
            }
        }

        //设置键值对的值
        public static int? setAppValue(string key, string value)
        {
            #region 原始版
            System.Configuration.Configuration config = System.Configuration.
                ConfigurationManager.OpenExeConfiguration(
                System.Configuration.ConfigurationUserLevel.None);
            int saveTag = 0;
            if (config.AppSettings.Settings[key] != null)
            {
                config.AppSettings.Settings[key].Value = value;
                saveTag = 0;
            }
            else
            {
                config.AppSettings.Settings.Add(key, value);
                saveTag = 1;
            }
            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            return saveTag;
            #endregion

            #region 第一次修改版
            //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //int saveTag = 0;
            //if (config.AppSettings.Settings[key] != null)
            //{
            //    config.AppSettings.Settings.Remove(key);
            //    //config.AppSettings.Settings.Add(key, value);
            //    config.Save(ConfigurationSaveMode.Modified);
            //    saveTag = 0;
            //}
            //else
            //{
            //    config.AppSettings.Settings.Add(key, value);
            //    saveTag = 1;
            //}
            //ConfigurationManager.RefreshSection("appSettings");
            //return saveTag;
            #endregion

            #region 二次修改版
            //System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            //xmldoc.Load("ClientApplication.EXE.Config");
            //foreach (System.Xml.XmlNode xnode in xmldoc["configuration"]["appSettings"])
            //{
            //    if (xnode.Name == "add")
            //    {
            //        if (xnode.Attributes.GetNamedItem("key").Value == key)
            //        {
            //            xnode.Attributes.GetNamedItem("value").Value = value;
            //        }
            //    }
            //    xmldoc.Save("App.Config");
            //}
            //return 1;
            #endregion

            #region 三次修改

            //XmlDocument xmlDoc = new XmlDocument();
            //string s = System.Windows.Forms.Application.StartupPath + "/ClientApplication.exe.config";
            //xmlDoc.Load(s);
            //XmlNode node = xmlDoc.SelectSingleNode("//appSettings");
            //XmlElement element = (XmlElement)node.SelectSingleNode(@"//add key=""IpPort""");
            // if (element != null)
            //{
            //    element.SetAttribute("value", value);
            //}
            //xmlDoc.Save(s);
            //xmlDoc = null;
            //return 1;
            #endregion
        }

        //设置连接字符串
        public static int? setConnection(string conKey, string dataSource, string initialCatalog)
        {
            if (string.IsNullOrEmpty(conKey)) return null;
            if (string.IsNullOrEmpty(dataSource)) return null;
            if (string.IsNullOrEmpty(initialCatalog)) return null;

            int saveTag = 0;
            System.Configuration.Configuration config =
                System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            string conncectionStr = string.Format(
                "Data Source={0};Initial Catalog={1};Integrated Security=True",
                dataSource, initialCatalog);

            if (config.ConnectionStrings.ConnectionStrings[conKey] == null)
            {
                System.Configuration.ConnectionStringSettings csSettings = new System.Configuration.ConnectionStringSettings(conKey, conncectionStr, "System.Data.SqlClient");
                config.ConnectionStrings.ConnectionStrings.Add(csSettings);
                saveTag = 0;
            }
            else
            {
                config.ConnectionStrings.ConnectionStrings[conKey].ConnectionString = conncectionStr;
                saveTag = 1;
            }
            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            return saveTag;
        }

        //获得连接字符串
        public static string getConnection(string conKey)
        {
            if (string.IsNullOrEmpty(conKey)) return null;
            System.Configuration.ConnectionStringSettings cons = System.Configuration.ConfigurationManager.ConnectionStrings[conKey];

            if (cons == null) return null;
            return cons.ConnectionString;
        }

        public static void getConfig()
        {
              Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
              ServiceModelSectionGroup serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);  
              ClientSection clientSection = serviceModelSectionGroup.Client;  
              foreach(ChannelEndpointElement item in clientSection.Endpoints) 
              { 
                  MessageBox.Show(item.Address.Host); 
              } 
        }
         
        public static void ChanageConfig(string serverIp) 
        { 
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
            ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"]; 
            ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup; 
            ClientSection clientSection = serviceModelSectionGroup.Client; 
            
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                string[] str = item.Address.ToString().Split('/');
                string pattern ="";
                for (int i = 0; i < str.Length-1; i++)
                    pattern += str[i] + '/';
                string address = item.Address.ToString();
                string replacement = string.Format("{0}", serverIp);
                address = Regex.Replace(address, pattern, replacement); 
                item.Address = new Uri(address);
            } 
            config.Save(ConfigurationSaveMode.Modified); 
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

        public static void ChangeServiceConfig(string serverIp)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
            ServicesSection serviceSection = serviceModelSectionGroup.Services;

            foreach (ServiceElement item in serviceSection.Services)
            {
                string address = item.Host.BaseAddresses[0].BaseAddress;
                string[] str = address.Split('/');
                string pattern = "";
                for (int i = 0; i < str.Length - 1; i++)
                    pattern += str[i] + '/';
                string replacement = string.Format("{0}", serverIp);
                address = Regex.Replace(address, pattern, replacement);
                item.Host.BaseAddresses[0].BaseAddress = address;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }
    }
}
